package com.wkk.service.impl;

import com.wkk.entity.*;
import com.wkk.mapper.CoachMapper;
import com.wkk.mapper.CourseMapper;
import com.wkk.mapper.UserMapper;
import com.wkk.service.CoachService;
import com.wkk.service.CourseService;
import com.wkk.util.GeneralCalculation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;

@Service
public class CoachServiceImpl implements CoachService {

    @Autowired
    private CoachMapper coachMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public void userConnectCoach(User user) {
        coachMapper.updateUserConnectCoach(user);
    }

    @Override
    public void userConnectCoachSuccess(User user) {
        Timestamp timestamp = new Timestamp(new Date().getTime());
        user.setGetCidTime(timestamp.toString());
        Calendar calendar = Calendar.getInstance();
        coachMapper.updateUserConnectCoachSuccess(user);//将教练确认的时间更新，实现会员与教练连接

        //声明这个年份月份的业绩---用于查询
      /*  CoachPerformance nowPerformance = new CoachPerformance(user.getCid(),calendar.get(Calendar.MONTH) + 1,calendar.get(Calendar.YEAR));
        CoachPerformance coachPerformance = coachMapper.selectOneP(nowPerformance);
        if(coachPerformance==null){//如果当年当月的该教练业绩不存在，则先添加此业绩,再进行更新学员个数
            coachMapper.insertPerformance(nowPerformance);
            CoachPerformance coachPerformance1 = coachMapper.selectOneP(nowPerformance);
            coachMapper.updatePStudentCount(coachPerformance1);
        }else{
        coachMapper.updatePStudentCount(coachPerformance);//连接成功后更新本月教练的学员个数
        }*/
    }

    @Override
    public void userConnectCoachStop(User user) {
        coachMapper.updateStopCoach(user);
    }

    @Override
    public Coach selectOneCoach(Integer cid) {
        Coach coach = coachMapper.selectOneByCid(cid);
        List<CoachPerformance> coachPerformances = coachMapper.selectListPerformanceByCid(cid);
        if(coachPerformances!=null) {
            coach.setCoachPerformances(coachPerformances);//该教练所有业绩信息
        }
        List<User> userList = coachMapper.selectStudentsByCid(cid);
        if(userList!=null) {
            coach.setUsers(userList);//该教练所有学员信息
        }
        //获取该教练的登录信息

        //获取该教练的所有荣誉

        return coach;
    }

    @Override
    public List<Coach> selectListOrderByRank(String condition,Integer mouth,Integer year) {
        //如果没有添加条件则默认为当前月份、年份
        Calendar calendar = Calendar.getInstance();
        if(mouth==0&&condition.equals("mouth")){
            mouth = calendar.get(Calendar.MONTH) + 1;
        }
        if(year==0){
            year = calendar.get(Calendar.YEAR);
        }
        int temp = 0;
        List<Coach> coaches = coachMapper.selectListOrderByRank(); //第一次获取未赋值排名的所有教练信息
        List<CoachPerformance> coachPerformances = null; //一个教练拥有很多条业绩数据(业绩根据，年，月会有不同的数据信息)
        for(Coach coach : coaches){
            int totalCourse = 0;
            int totalStudent = 0;
            int totalComment = 0;
            coach.setTotalPerformances(0);
            if(condition.equals("total")){//业绩总榜
                coachPerformances = coachMapper.selectListPerformanceByCid(coach.getCid());
            }
            if(condition.equals("mouth")){//月度业绩榜
                coachPerformances = coachMapper.selectListPerformanceByTime(new CoachPerformance(coach.getCid(),mouth,year));
            }
            if(condition.equals("year")){//年度业绩榜
                coachPerformances = coachMapper.selectListPerformanceByTime(new CoachPerformance(coach.getCid(),null,year));
            }
            if(coachPerformances==null){//如果当月没有业绩则显示0
                coach.setTotalPerformances(0);
            }else {
                for (CoachPerformance coachPerformance : coachPerformances) {//求出每个教练的 总学生数，总课时数 以及总公共课数
                    totalCourse += coachPerformance.getCourseCount();
                    totalStudent += coachPerformance.getStudentCount();
                    totalComment += coachPerformance.getCommentCount();
                }

                //通过教练的类型 来拟定私教课的价格
                if (coach.getMold().equals("总教练")) {
                    temp = 500;
                } else if (coach.getMold().equals("高级私人教练")) {
                    temp = 300;
                } else if(coach.getMold().equals("专家培训师")){
                    temp = 600;
                }else {
                    temp = 200;
                }
                //赋值业绩总量，用于实现排名
                coach.setTotalPerformances(totalCourse * temp + totalStudent * 100 + totalComment * 200);
            }
        }
        //通过排序总业绩，对教练进行排名
        Collections.sort(coaches, new Comparator<Coach>() {
            @Override
            public int compare(Coach o1, Coach o2) {
                int difference = o1.getTotalPerformances()-o2.getTotalPerformances();
                if(difference < 0){
                    return 1;
                }else if(difference > 0){
                    return -1;
                }
                return 0;
            }
        });
        int i = 1;
        for(Coach coach:coaches){
            coach.setRank(i);
            coachMapper.updateCoachRank(coach);
            i++;
        }
        return coachMapper.selectListOrderByRank();//最后在重新升序获取排好序的教练信息
    }

    @Override
    public List<Coach> selectListByMold(String mold) {
        return coachMapper.selectListByMold(mold);
    }

    @Override
    public User addOrUpdateCoach(Coach coach) {
        User user = new User();
        List<User> users =  userMapper.selectList();
        for(User one :users){
            //如果存在手机号已被其他用户占用则无法添加或更新,返回一个空的用户信息
            if(one.getMobile().equals(coach.getMobile())){
                user.setUsername("error");
                return user;
            }
        }
        //通过传入的值进行判断教练是否存在，若是存在则更新信息，若是不存在则添加教练信息
        Coach coach1 = coachMapper.selectOneByNameAndMobile(coach);
        if(coach1!=null){
            //如果存在该教练,则更新该教练的信息
            coachMapper.updateCoach(coach);
            user.setUsername("update");
        }else {
            //如果不存在,则添加教练信息的同时,添加教练用户表信息
            coachMapper.insertCoach(coach);
            user.setMobile(coach.getMobile());
            user.setUsername(coach.getCname());
            user.setPassword(coach.getMobile());
            user.setLevel("coach");
            user.setCreateTime(new Timestamp(new Date().getTime()).toString());
            userMapper.insertOne(user);
        }
        return user;
    }

    @Override
    public boolean updateCoachMold(Coach coach) {
        int i = 0;
        i = coachMapper.updateCoachMold(coach);
        return i==1?true:false;
    }

    @Override
    public boolean deleteCoach(Integer cid) {
        int i = 0;
        Coach coach = coachMapper.selectOneByCid(cid);

        //如果该教练还有在教课程，则无法删除该教练
        //1、查找该教练的所有课程。2、查找所有预约信息。3、判断预约信息中是否存在该课，存在则返回false
        //(教练名字与课程信息一对多对应)
        List<Course> courses = courseMapper.selectListByTeacher(coach.getCname());
        //如果该数组为空，则直接可以删除
        //如果不为空，则进行下一步
        if(courses!=null){
            for(Course course:courses){
                List<MyCourse> myCourses = courseMapper.queryMyCoursesByCid(course.getCid());
                if(myCourses!=null){
                    return false;
                }
            }
        }

        User user = userMapper.selectOneByNameAndMobile(new User(coach.getCname(),coach.getMobile()));
        userMapper.deleteUser(user.getUid());
        i = coachMapper.deleteCoachByCid(cid);
        return i==1?true:false;
    }

    @Override
    public PerformanceInfo getCoachPerformanceInfo(Integer cid) {
        Coach coach = coachMapper.selectOneByCid(cid);//获取当前教练信息
        Integer basicIncome = 2000;//由于之前数据库没有设计全面,所以将底薪设死
        PerformanceInfo performanceInfo = new PerformanceInfo();
        List<PerformanceChild> performanceChildren = new ArrayList<>();
        //获取当前时间的本教练业绩--用于查询数据（工具类中）
        List<CoachPerformance> performances = new GeneralCalculation().getPerforances(cid);
        for(CoachPerformance coachPerformance:performances){
            //第一步：从数据库查找该业绩
            CoachPerformance coachPerformance1 = coachMapper.selectOneP(coachPerformance);
            //第二步：判断该业绩是否存在,如果不存在则插入该数据,且赋值本教练本月的业绩情况
            PerformanceChild performanceChild = new PerformanceChild();//创建子业绩
            if(coachPerformance1==null){
                coachMapper.insertPerformance(coachPerformance);
                //子业绩赋值
                performanceChild.setBasicIncome(basicIncome);
                performanceChild.setMonth(coachPerformance.getTeachMouth()+"月");
                performanceChild.setCommentIncome(0);
                performanceChild.setCourseIncome(0);
                performanceChild.setMemberIncome(0);
            }else{//第二步：如果存在则获取其内容并进行相对的赋值操作
                //通过该业绩中该课程的编号获取该课程的所有信息
                Integer price = 200;
                Integer commentCount = coachPerformance1.getCommentCount();
                Integer studentCount = coachPerformance1.getStudentCount();
                Integer courseCount = coachPerformance1.getCourseCount();
                performanceChild.setBasicIncome(basicIncome);
                performanceChild.setMonth(coachPerformance1.getTeachMouth()+"月");
                performanceChild.setCommentIncome(commentCount*100);
                performanceChild.setCourseIncome(courseCount*price*3/10);
                performanceChild.setMemberIncome(studentCount*100);
            }
            performanceChildren.add(performanceChild);//将子业绩赋值到八个月的业绩之中
        }
        Integer nowMonthIncome = performanceChildren.get(0).getBasicIncome()+performanceChildren.get(0).getCommentIncome()
                +performanceChildren.get(0).getCourseIncome()+performanceChildren.get(0).getMemberIncome();
        performanceInfo.setNowMonthIncome(nowMonthIncome);//将本月的收入赋值
        performanceInfo.setPerformanceChild(performanceChildren);//将过去八个月的所有业绩赋值

        List<CoachPerformance> coachPerformanceList =  coachMapper.selectListPerformanceByCid(cid);
        Integer memberHistory = 0;
        for(CoachPerformance coachPerformance:coachPerformanceList){
            memberHistory +=coachPerformance.getStudentCount();
        }
        performanceInfo.setMemberHistory(memberHistory);//历史学员个数
        List<User> userList = userMapper.selectList();
        Integer memberCount = 0;
        for(User user:userList){
            if(user.getCid()==cid){
                memberCount += 1;
            }
        }
        performanceInfo.setMemberCount(memberCount);//当前学员个数

        return performanceInfo;
    }

    @Override
    public boolean addHonor(Honor honor) {
        int i = 0;
        i = coachMapper.insertHonor(honor);
        return i==1?true:false;
    }

    @Override
    public boolean deleteHonor(Integer id) {
        int i = 0;
        i = coachMapper.deleteHonorById(id);
        return i==1?true:false;
    }

    @Override
    public boolean updateHonor(Honor honor) {
        int i = 0;
        i = coachMapper.updateHonor(honor);
        return i==1?true:false;
    }

    @Override
    public List<Honor> selectListHonorByCid(Integer cid) {
        return coachMapper.selectListHonorByCid(cid);
    }

    @Override
    public boolean addOrUpdateHonor(Honor honor) {
        int i = 0;
        Honor honor1 = coachMapper.selectOneHonorById(honor.getId());
        if(honor1==null){
            i = coachMapper.insertHonor(honor);
        }else {
            i = coachMapper.updateHonor(honor);
        }
        return i==1?true:false;
    }

}
